package com.jlz.service.email;

import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.julewa.freemarker.FreemarkerBuilder;
import com.julewa.freemarker.FreemarkerMethod;

public class FreemarkerEmailBuilder{
	private BinaryResources resources = null;
	private MimeMessage message = null;
	private FreemarkerBuilder builder = null;
	private MimeMessageHelper m = null;
	//
	public FreemarkerEmailBuilder(FreemarkerBuilder builder, BinaryResources resources, MimeMessage message){
		this.message = message;
		this.builder = builder;
		this.resources = resources;
		//
		try {
			m = new MimeMessageHelper(message,true,"UTF-8");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	// \
	private FreemarkerMethod titleSetter = new FreemarkerMethod(){
		@Override
		public Object execute(Object... args) {
			try {
				m.setSubject(args[0].toString());
			} catch (MessagingException e) {
				e.printStackTrace();
			}
			return "";
		}
	};
	
	private FreemarkerMethod inlineSetter = new FreemarkerMethod(){
		private Set<String> used = new HashSet<String>();
		@Override
		public Object execute(Object... args) {
			String arg = args[0].toString();
			if(used.contains(arg)){
				return "cid:"+arg;
			}
			used.add(arg);
			Resource r = resources.getResource(arg);
			if(r == null)return "";
			try {
				m.addInline(arg, r);
				return "cid:"+arg;
			} catch (Exception e) {
				return "";
			}
		}
	};
	
	public MimeMessage build(String from, String to) throws MessagingException{
		builder.put("@title", titleSetter);
		builder.put("@inline", inlineSetter);
		StringWriter writer = new StringWriter();
		builder.build(writer);
		//
		m.setFrom(from);
		m.setTo(to);
		m.setText(writer.getBuffer().toString(), true);
		//
		return message;
	}
	
}
